<style lang="scss" scoped>
/deep/ .el-dialog__header{
  padding: 0 0 0 0 !important;
}
/deep/ .el-dialog__body{
  padding: 0 0 0 0 !important;
  height: 100%;
}
// .canvasUserPhotoCamera{
//   width: 100%;
//   height: 100%;
//   overflow: hidden;
// }
.headerBox{
  padding: 18px 20px;
}
.closeBtn{
  position: absolute;
  right: 20px;
  top: 20px;
}
.camaraBox{
  // border: 1px solid #999999;
  width: 200px;
  height: 200px;
  border-radius: 100%;
}
.el-icon-camera-solid{
  font-size: 100px;
}
</style>
<template>
  <!-- width="640px"
  height="900px"
  top="0px" -->
  <el-dialog
    :close-on-click-modal="true"
    :close-on-press-escape="false"
    :show-close="false"
    append-to-body
    fullscreen
    :visible.sync="cameravisible"
    :destroy-on-close="true"
    @open="cameraOpen"
    @close="cameraClose"
    class="">
    <div slot="title" style="height: 0;"></div>
    <div class="flex flex-row h-100">
      <div class="video-container h-100" v-loading="videoLoading">
        <video class="video" id="video" :style="videoStyle" autoplay playsinline></video>
        <canvas class="canvasUserPhotoCamera" id="canvasUserPhotoCamera" :width="videoWidth" :height="videoHeight" style="display: none;"></canvas>
        <!-- <video class="videoUserPhotoCamera" id="videoUserPhotoCamera" :style="videoStyle" preload autoplay loop muted></video>
        <canvas class="canvasUserPhotoCamera" id="canvasUserPhotoCamera" :width="videoWidth" :height="videoHeight" style="display: none;"></canvas> -->
      </div>
      <div class="flex flex-column pos-rel flex-1">
        <div class="flex flex-row justify-between align-center headerBox">
          <div class="fs-22 font-bold">摄像拍照</div>
          <el-button @click="closeDialog">关闭</el-button>
        </div>
        <div class="flex-1 flex flex-column justify-center align-center">
          <div class="camaraBox flex flex-column justify-center align-center" :style="{'border': `1px solid ${cameraColor}`}" @click="setImage">
            <i class="el-icon-camera-solid" :style="{'color': cameraColor}" @mouseover="cameraIconMouseover" @mouseleave="cameraIconMouseleave"></i>
          </div>
          <!-- <video id="video" width="500px" height="500px" autoPlay="autoplay" controls="controls"></video> -->
          <!-- <el-radio-group v-model="typeRadio" class="mar-t-20" @input="typeInput">
            <el-radio-button label="A4"></el-radio-button>
            <el-radio-button label="A5/A6"></el-radio-button>
          </el-radio-group> -->
          <!-- <div>
            <div class="label">Pan:</div>
            <input name="pan" type="range" disabled>
          </div>
          <div>
            <div class="label">Tilt:</div>
            <input name="tilt" type="range" disabled>
          </div>
          <div>
            <div class="label">Zoom:</div>
            <input name="zoom" type="range" disabled>
          </div> -->
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { applyimagepost } from '@/api/api.js'
// import { applyimagepost, fileUp } from '@/api/api.js'
import { compressBase64Image, getDateYMDHMS } from '@/utils/utils.js'
import { getToken } from '@/utils/auth.js'
import { sysAppId } from '@/settings'

export default {
  data() {
    return {
      typeRadio: 'A5/A6',
      cameraColor: '#999999',
      colorDefault: '#999999',
      colorActive: '#3478ff',
      cameravisible: false,
      videoWidth: 580,
      videoHeight: 817,
      videoStyle: {
        width: '580px',
        height: '817px'
      },
      videoLoading: false,
      cvsCamera: null,
      ctxCamera: null,
      videoUserPhotoCamera: null,
      imgSrc: [],
      srcList: [],
      imgBaseUrl: window.g.API_ROOT_RIS
    }
  },
  props: {
    row: {
      type: Object,
      default: () => { }
    }
  },
  computed: {
    appConfig() {
      return this.$store.state.settings.appConfig
    },
    saveByPic() {
      return this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.saveByPic || false
    },
    picRatio() {
      return this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.picRatio || 1
    }
  },
  created() {
    // console.log('getDateYMDHMS(new Date())', getDateYMDHMS(new Date()))
    this.calSize(this.typeRadio)
  },
  methods: {
    calSize(e) {
      if (e == 'A4') {
        // console.log('created=>cameraPhoto', document.documentElement.clientHeight)
        this.videoStyle.height = document.documentElement.clientHeight + 'px'
        this.videoStyle.width = (document.documentElement.clientHeight * 1.41 + 200).toFixed(2) + 'px'
        this.videoHeight = Number(document.documentElement.clientHeight)
        this.videoWidth = Number((document.documentElement.clientHeight * 1.41 + 200).toFixed(2))
        // console.log('this.videoHeight', this.videoHeight)
        // console.log('this.videoWidth', this.videoWidth)
      } else if (e == 'A5/A6') {
        // console.log('created=>cameraPhoto', document.documentElement.clientHeight)
        this.videoStyle.height = (document.documentElement.clientHeight) + 'px'
        this.videoStyle.width = (document.documentElement.clientHeight / 1.1).toFixed(2) + 'px'
        this.videoHeight = Number(document.documentElement.clientHeight)
        this.videoWidth = Number((document.documentElement.clientHeight / 1.1).toFixed(2))
        // console.log('this.videoHeight', this.videoHeight)
        // console.log('this.videoWidth', this.videoWidth)
      }
    },
    typeInput(e) {
      console.log('typeInput', e)
      this.calSize(e)
    },
    cameraIconMouseleave() {
      this.cameraColor = '#999999'
    },
    cameraIconMouseover() {
      this.cameraColor = '#3478ff'
    },
    cameraDlgOpen() {
      this.cameravisible = true
    },
    closeDialog() {
      this.cameravisible = false
    },
    // 打开
    cameraOpen() {
      console.log('clientHeight', document.documentElement.clientHeight)
      this.$nextTick(() => {
        this.videoLoading = true
        // 开启摄像头
        // this.getCompetence()
        this.getMedia()
      })
    },
    // 关闭
    cameraClose() {
      // 关闭摄像头
      if (this.videoUserPhotoCamera && this.videoUserPhotoCamera.srcObject) {
        this.videoUserPhotoCamera.srcObject.getTracks()[0].stop()
      }
    },
    handleSuccess(stream) {
      const video = document.querySelector('video')
      const videoTracks = stream.getVideoTracks()
      video.srcObject = stream
      const capabilities = videoTracks[0].getCapabilities()
      const settings = videoTracks[0].getSettings()
      for (const ptz of ['pan', 'tilt', 'zoom']) {
        if (!(ptz in settings)) {
          continue
        }
        const input = document.querySelector(`input[name=${ptz}]`)
        input.min = capabilities[ptz].min
        input.max = capabilities[ptz].max
        input.step = capabilities[ptz].step
        input.value = settings[ptz]
        input.disabled = false
        input.oninput = async event => {
          try {
            const constraints = { advanced: [{ [ptz]: input.value }] }
            await videoTracks[0].applyConstraints(constraints)
          } catch (err) {
            console.error('applyConstraints() failed: ', err)
          }
        }
      }
    },
    // getMedia() {
    //   let video = document.getElementById('video')
    //   let constraints = {
    //     video: { width: 400, height: 500 },
    //     audio: false
    //   }
    //   navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia
    //   let promise = navigator.mediaDevices.getUserMedia(
    //     constraints,
    //     function (stream) {
    //       video.src = stream
    //       video.play()
    //     },
    //     function (error) {
    //       console.log(error)
    //     }
    //   )
    //   promise.then(function (MediaStream) {
    //     video.srcObject = MediaStream
    //     video.play()
    //   })
    // },
    getMedia() {
      var _this = this
      _this.videoUserPhotoCamera = document.getElementById('video')
      this.cvsCamera = document.getElementById('canvasUserPhotoCamera')
      this.ctxCamera = this.cvsCamera.getContext('2d')
      let constraints = {
        video: {
          width: this.videoWidth,
          height: this.videoHeight
        },
        audio: false
      }
      navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia
      let promise = navigator.mediaDevices.getUserMedia(
        constraints,
        function (stream) {
          // video.src = stream
          // video.play()
          _this.videoUserPhotoCamera.src = stream
          _this.videoUserPhotoCamera.play()
          _this.videoLoading = false
        },
        function (error) {
          console.log(error)
          _this.videoUserPhotoCamera = null
          _this.$message.warning('不支持访问用户媒体！')
          _this.videoLoading = false
        }
      )
      promise.then(function (MediaStream) {
        _this.videoUserPhotoCamera.srcObject = MediaStream
        _this.videoUserPhotoCamera.play()
        _this.videoLoading = false
      })
    },
    // 调用权限（打开摄像头功能）
    getCompetence() {
      var _this = this
      this.cvsCamera = document.getElementById('canvasUserPhotoCamera')
      this.ctxCamera = this.cvsCamera.getContext('2d')
      this.videoUserPhotoCamera = document.getElementById('videoUserPhotoCamera')
      // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {}
      }
      // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
      // 使用getUserMedia，因为它会覆盖现有的属性。
      // 这里，如果缺少getUserMedia属性，就添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia
          // 有些浏览器不支持，会返回错误信息
          // 保持接口一致
          if (!getUserMedia) {
            return Promise.reject(new Error('getUserMedia is not implemented in this browser'))
          }
          // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject)
          })
        }
      }
      const constraints = {
        audio: false,
        video: {
          pan: true,
          tilt: true,
          zoom: true,
          width: this.videoWidth,
          height: this.videoHeight
        }
      }
      // var constraints = { audio: false, video: { width: this.videoWidth, height: this.videoHeight }} // 原来的样子
      navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
        // _this.handleSuccess(stream)
        // 旧的浏览器可能没有srcObject
        if ('srcObject' in _this.videoUserPhotoCamera) {
          console.log('========1111111')
          _this.videoUserPhotoCamera.srcObject = stream
          _this.videoUserPhotoCamera.play()
          _this.videoLoading = false
        } else {
          console.log('========222222')
          // 避免在新的浏览器中使用它，因为它正在被弃用。
          _this.videoUserPhotoCamera.src = window.URL.createObjectURL(stream)
        }
      }).catch(err => {
        console.error('catch', err)
        _this.videoUserPhotoCamera = null
        _this.videoLoading = false
        _this.$message.warning('不支持访问用户媒体！')
      })
    },
    // 使用示例
    // compressBase64Image('data:image/png;base64,...', 800, 600).then(compressedBase64 => {
    //   console.log(compressedBase64); // 输出压缩后的base64
    // }).catch(error => {
    //   console.error(error);
    // });
    // 绘制图片（拍照功能）
    setImage() {
      var _this = this
      if (!this.cvsCamera || !_this.videoUserPhotoCamera) return
      // 点击，canvas画图
      _this.ctxCamera.drawImage(_this.videoUserPhotoCamera, 0, 0, _this.videoWidth, _this.videoHeight)
      // 获取图片base64链接
      var image = this.cvsCamera.toDataURL('image/jpeg')
      // if(_this.imgSrc.length>=10){
      //   _this.imgSrc.splice(0,1)
      //   _this.srcList.splice(0,1)
      // }
      // _this.imgSrc.push(image)
      // _this.srcList.push(image)
      // this.$emit('cameraPhoto', image)
      compressBase64Image(image, 1754, 1240, 'image/jpeg', this.picRatio).then(compressedBase64 => {
        console.log('compressedBase64', compressedBase64) // 输出压缩后的base64
        this.cameraPhoto(compressedBase64)
        this.closeDialog()
      }).catch(error => {
        console.error(error)
      })
    },
    flrStr(val) {
      return val === null ? '' : val
    },
    // 申请单上传 以base64方式存储
    uploadByBase64(file) {
      let imageType = file.split(';')[0].split('/')[1]
      console.log('imageType', imageType)
      // 调用上传纸质申请单图片的接口
      let params = {
        hospitalCode: this.row.applyHospitalCode,
        accessNo: this.flrStr(this.row.accessionNo),
        applyImageBase64: file.split(';')[1].split(',')[1],
        imageCategory: '申请单',
        imageType: imageType
      }
      applyimagepost(params).then(res => {
        if (res && res.code == 10000) {
          this.$emit('postSuccess', 1)
          this.$message.success(res.message)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    cameraPhoto(file) {
      console.warn('this.row=>', this.row)
      console.log('拍照后获取到base64位的图片', file)
      if (this.saveByPic) {
        this.uploadByFile(file)
      } else {
        this.uploadByBase64(file)
      }
    },
    // 申请单上传 以图片方式存储
    uploadByFile(file) {
      // if(!this.avatarFile){
      //   resolve()
      //   return
      // }
      let token = getToken()
      console.log('token', token)
      // const token = tokenInfo ? tokenInfo.accessToken : ''
      const fileOfBlob = this.dataURLtoFile(file, '申请单' + new Date().getTime() + '.jpg') // base64转文件
      console.log('fileOfBlob', fileOfBlob)
      let formData = new FormData()
      formData.append('file', fileOfBlob)
      // fileUp(formData).then(res => {
      //   console.log('fileUp=>res', res)
      //   if (res && res.code == 10000) {
      //     // this.$message.success(res.message)
      //   } else {
      //     // this.$message.error(res.message)
      //   }
      // })
      let url = `${this.imgBaseUrl}/api/v1/file/6?HospitalCode=${this.row.applyHospitalCode}&Accessno=${this.flrStr(this.row.accessionNo)}&RegisterDate=${getDateYMDHMS(new Date())}`
      let ajaxhttp = new XMLHttpRequest() // 创建ajax对象
      ajaxhttp.open('POST', url, true) // （规定请求的类型）请求方式 请求地址 同步还是异步
      if (token) {
        ajaxhttp.setRequestHeader('Authorization', 'Bearer ' + token)
        ajaxhttp.setRequestHeader('sysappid', sysAppId)
      }
      ajaxhttp.send(formData) // （发送请求到服务器）
      ajaxhttp.onreadystatechange = () => { // 请求响应
        console.log('ajaxhttp', ajaxhttp)
        // 固定写法 readyState 表示 ajax的状态
        // ajax的状态总共有（0 1 2 3 4 ）五种状态 状态为4表示请求完成 status === 200表示成功
        if (ajaxhttp.readyState == 4) { // 请求完成
          if (ajaxhttp.status === 200) {	// http请求状态为200 成功
            // this.$emit('postSuccess', 1)
            console.log('ajaxhttp.responseText', ajaxhttp.responseText)
            console.log('ajaxhttp.responseText.Context', JSON.parse(ajaxhttp.responseText).Context)
            // console.log('ajaxhttp.responseText.Context.RelativePath', ajaxhttp.responseText.Context.RelativePath)
            const relativePath = JSON.parse(ajaxhttp.responseText).Context.RelativePath
            console.log('relativePath', relativePath)
            this.uploadByFilePath(relativePath)
            // this.$message.success('上传成功')
          } else { // 状态码不为200 失败
            this.$message.success('上传失败:' + ajaxhttp.status)
            // error && error(ajaxhttp.status)	// 失败的回调
            // reject(ajaxhttp.status) // promise 失败 返回
          }
        }
      }
    },
    // 申请单上传 以文件路径的方式上传
    uploadByFilePath(filePath) {
      console.log('uploadByFilePath=>now', new Date().getTime())
      let imageType = filePath.split('.')[1]
      // if (this.saveByPic) {
      //   imageType = filePath.split('.')[1]
      // } else {
      //   imageType = filePath.split(';')[0].split('/')[1]
      // }
      console.log('imageType', imageType)
      // 调用上传纸质申请单图片的接口
      let params = {
        hospitalCode: this.row.applyHospitalCode,
        accessNo: this.flrStr(this.row.accessionNo),
        imageFileName: filePath,
        imageCategory: '申请单',
        imageType: imageType
      }
      applyimagepost(params).then(res => {
        if (res && res.code == 10000) {
          this.$message.success(res.message)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // base64转文件
    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(',')
      var mime = arr[0].match(/:(.*?);/)[1]
      var bstr = atob(arr[1])
      var n = bstr.length
      var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], filename, { type: mime })
    }
  }
}
</script>
